package com.ifreshwing.https;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class NetWorkConnector {

	private static Context context;

	private static final String TAG = "NetWorkConnector";
	private static NetWorkConnector netWorkConnector = new NetWorkConnector();
	private long currentTime = System.currentTimeMillis();

	private NetWorkConnector() {
	}

	public static NetWorkConnector getNetWorkConnector(Context c) {
		context = c;
		return netWorkConnector;
	}

	public static NetWorkConnector getNetWorkConnector() {
		return netWorkConnector;
	}

	public Object sendRequest(int requestId, int type, String url,
			Map<String, String> map) {
		return requestData(requestId, type, url, map);
	}

	private static String response;
	private Object object;

	public Object requestData(int requestId, int type, String url,
			Map<String, String> map) {
		@SuppressWarnings("unused")
		Gson gson = new Gson();
		try {
			if (NetworkDetector.isNetworkConnected(context)) {
				response = doHttpRequest(type, url, map);
			} else {
				response = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response = null;
		}

		// 对response 进行解析
		switch (requestId) {
		default:
			object = response;
			break;
		}
		return object;
	}

	/**
	 * 访问网络
	 * 
	 * @param type
	 *            请求类型
	 * @param url
	 *            请求url
	 * @param map
	 *            请求参数 map集合
	 * @return response 结果(String)
	 * @throws Exception
	 */
	private String doHttpRequest(int type, String url, Map<String, String> map)
			throws Exception {

		String resonseData = null;
		switch (type) {
		// get请求
		case HttpConstantValue.TYPE_GET:

			StringBuffer buffer = new StringBuffer(url);

			if (map != null && map.size() > 0) {

				for (Entry<String, String> entry : map.entrySet()) {
					buffer.append(entry.getKey()).append("=")
							.append(entry.getValue()).append("&");

				}
			}
			buffer.deleteCharAt(buffer.length() - 1);
			String requestUrl = buffer.toString().trim();

			// Log.e("#############3", requestUrl);

			URL urlPath = new URL(requestUrl);

			HttpURLConnection conn = (HttpURLConnection) urlPath
					.openConnection();
			conn.setRequestMethod("GET");

			conn.setConnectTimeout(HttpConstantValue.CONNECT_TIMEOUT);
			conn.setRequestProperty("encoding", "UTF-8");
			conn.connect();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				resonseData = new String(StreamTools.readInputStream(conn
						.getInputStream()));

			} else {
				resonseData = null;

				Log.w(TAG, "IOException connect exception, response code is"
						+ conn.getResponseCode());
			}
			break;

		case HttpConstantValue.TYPE_POST:
			HttpPost httpPost = new HttpPost(url);

			// 设置请求参数

			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					HttpConstantValue.CONNECT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams,
					HttpConstantValue.READ_TIMEOUT);

			// 拼装params
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(
					map.entrySet());
			Collections.sort(list, new Comparator<Entry<String, String>>() {
				// 升序排序
				public int compare(Entry<String, String> o1,
						Entry<String, String> o2) {
					return o1.getValue().compareTo(o2.getValue());
				}

			});

			for (Entry<String, String> entry : list) {
				params.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
			}

			// httpclient 进行请求
			HttpClient httpClient = HttpClientFactory.getHttpClient();

			httpPost.setEntity(new UrlEncodedFormEntity(params,
					HttpConstantValue.UTF_8));
			httpClient.getConnectionManager().closeExpiredConnections();
			httpPost.getParams().setBooleanParameter(
					CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
			HttpResponse httpResponse = httpClient.execute(httpPost);

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity httpEntity = httpResponse.getEntity();
				resonseData = EntityUtils.toString(httpEntity, "UTF-8");

			} else {
				resonseData = null;

			}
			break;

		case HttpConstantValue.TYPE_PUT:
			HttpPut httpput = new HttpPut(url);
			httpput.setHeader("Content-Type",
					"application/x-www-form-urlencoded; charset=utf-8");
			BasicHttpParams httpParamsput = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParamsput,
					HttpConstantValue.CONNECT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParamsput,
					HttpConstantValue.READ_TIMEOUT);

			// 拼装params
			List<NameValuePair> paramsput = new ArrayList<NameValuePair>();

			for (Entry<String, String> entry : map.entrySet()) {
				paramsput.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));

				// Log.d("mmmm----->", entry.getValue());

			}

			// httpclient 进行请求
			HttpClient httpClientput = HttpClientFactory.getHttpClient();

			httpput.setEntity(new UrlEncodedFormEntity(paramsput,
					HttpConstantValue.UTF_8));
			httpClientput.getConnectionManager().closeExpiredConnections();
			httpput.getParams().setBooleanParameter(
					CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
			HttpResponse httpResponseput = httpClientput.execute(httpput);

			if (httpResponseput.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity httpEntity = httpResponseput.getEntity();
				// resonseData = EntityUtils.toString(httpEntity);
				resonseData = EntityUtils.toString(httpEntity, "UTF-8");
			} else {
				resonseData = null;

			}
			break;

		case HttpConstantValue.TYPE_DELETE:

			StringBuffer bufferdelete = new StringBuffer(url);

			if (map != null && map.size() > 0) {

				for (Entry<String, String> entry : map.entrySet()) {
					bufferdelete.append(entry.getKey()).append("=")
							.append(entry.getValue()).append("&");

				}
			}
			bufferdelete.deleteCharAt(bufferdelete.length() - 1);
			String requestUrldelete = bufferdelete.toString().trim();

			if (url.contains("productsDetail")) {
				requestUrldelete = url;
			}

			// Log.d("url---->", requestUrldelete);

			URL urlPathdelete = new URL(requestUrldelete);

			HttpURLConnection conndelete = (HttpURLConnection) urlPathdelete
					.openConnection();
			conndelete.setRequestMethod("DELETE");

			conndelete.setConnectTimeout(HttpConstantValue.CONNECT_TIMEOUT);
			conndelete.setRequestProperty("encoding", "UTF-8");
			conndelete.connect();
			if (conndelete.getResponseCode() == HttpURLConnection.HTTP_OK) {
				resonseData = new String(StreamTools.readInputStream(conndelete
						.getInputStream()));

			} else {
				resonseData = null;
				Log.w(TAG, "IOException connect exception, response code is"
						+ conndelete.getResponseCode());
			}
			break;

		default:
			break;
		}

		return resonseData;
	}

}
